/** @method CustomForm
 *  @description 简单form表单组件
 *  @param {Array} formItems 传入的符合标准的表单组件组成的数组，必填
 *  @param {Function} createForm 将form暴露给父组件的回调，必填
 *  @param {Function} onHandleSubmit 提交回调，必填
 *  @param {Number} colNum flex布局下分几列，默认2，选填
 *  @param {String} className 最外层加class，用于控制样式,默认空 选填
 *  @param {String} confirmText 确定按钮文字 选填
 *  @param {Boolean} hideSubmit 是否隐藏提交按钮,默认false（不隐藏）
 *  @param {Function} closeModal 点击取消的回调方法
 *  @param {Object} children 子元素
 *
 */
import React from 'react';
import { Row, Col, Form, Button } from 'antd';
import FormItem from '../FormItem/index';
import './index.less';

function CustomForm(props) {
  const {
    formItems = [],
    createForm,
    onHandleSubmit,
    colNum = 2,
    hideSubmit = false,
    className = '',
    closeModal = null,
    form,
    children,
    loading = false,
  } = props;
  if (!createForm) {
    throw '@params createForm is require!';
  }
  if (!hideSubmit) {
    if (!onHandleSubmit) {
      throw '@params onHandleSubmit is require!';
    }
  }

  createForm && createForm(form);

  const onSubmit = (e) => {
    e.preventDefault();
    onHandleSubmit && onHandleSubmit();
  };
  const colSpan = 24 / colNum;
  return (
    <div className={`tantuer-form ${className}`}>
      <Form onSubmit={() => false} className='login-form' autoComplete='off'>
        <div className='tantuer-field-area'>
          {props.help && <div className='form-title'>{props.help}</div>}

          <Row type='flex'>
            {formItems.map((item, index) => {
              const even = index % 2 === 1; //偶数
              const evenClass = colNum === 2 && even ? 'even-label' : null;
              return (
                <Col className={evenClass} span={item.span ? item.span : colSpan} key={item.name}>
                  <FormItem {...props} form={form} item={item} colNum={colNum} />
                </Col>
              );
            })}
          </Row>
        </div>
        {children}
        {!hideSubmit && (
          <div className='form-btn'>
            <Button loading={loading} type='primary' onClick={onSubmit} className='login-form-button' autoFocus={true}>
              {props.confirmText || '确定'}
            </Button>
            {closeModal && (
              <Button className='login-form-button' onClick={() => closeModal && closeModal(true)}>
                取消
              </Button>
            )}
          </div>
        )}
      </Form>
    </div>
  );
}

export default Form.create()(CustomForm);
